<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">生产管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/sc/order' }">生产订单</el-breadcrumb-item>
        <el-breadcrumb-item>生产订单详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 订单信息 -->
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; color: #409EFF;">订单信息</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getStatusTagType(orderInfo.status)">{{ getStatusName(orderInfo.status) }}</el-tag>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">生产订单编号：</span>
            <span>{{ orderInfo.prodOrderCode || 'GD20231002101' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">客户名称：</span>
            <span>{{ orderInfo.customerName || '广汇商贸' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">销售单号：</span>
            <span>{{ orderInfo.salesOrderCode || 'PO20170725022' }}</span>
          </div>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">订单来源：</span>
            <span>{{ orderInfo.sourceType || '系统新增' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">备注：</span>
            <span>{{ orderInfo.remark || '-' }}</span>
          </div>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">创建时间：</span>
            <span>{{ orderInfo.createTime || '2020/09/01 10:40' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">创建人：</span>
            <span>{{ orderInfo.createBy || '林敏儿' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">最后更新时间：</span>
            <span>{{ orderInfo.updateTime || '2020/09/01 10:40' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="detail-item">
            <span class="label">最后更新人：</span>
            <span>{{ orderInfo.updateBy || '林敏儿' }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 产品信息 -->
    <el-card class="box-card" shadow="never" style="margin-top: 15px;">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; color: #409EFF;">产品信息</span>
      </div>
      <el-table :data="productList" stripe style="width: 100%">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="产品编码" prop="productCode" align="center" />
        <el-table-column label="产品名称" prop="productName" align="center" />
        <el-table-column label="规格" prop="productSfn" align="center" />
        <el-table-column label="计量单位" prop="productUnit" align="center" />
        <el-table-column label="交付日期" prop="deliveryDate" align="center" />
      </el-table>
    </el-card>
    
    <!-- 关联生产计划 -->
    <el-card class="box-card" shadow="never" style="margin-top: 15px;">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; color: #409EFF;">关联生产计划</span>
      </div>
      <el-table :data="planList" stripe style="width: 100%">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="生产计划编号" prop="plan_code" align="center" />
        <el-table-column label="计划状态" prop="status" align="center">
          <template slot-scope="scope">
            <el-tag :type="getPlanStatusTagType(scope.row.status)">{{ scope.row.status_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="优先级" prop="priority" align="center">
          <template slot-scope="scope">
            <el-tag :type="getPriorityTagType(scope.row.priority)">{{ scope.row.priority_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="产品编码" prop="product_code" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.product_code || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" prop="product_name" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.product_name || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计量单位" prop="unit" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.productUnit || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="规格" prop="specification" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.specification || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划产量" prop="qty" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.qty || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="报工数量" prop="report_qty" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.report_qty || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="销售单号" prop="sales_order_code" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sales_order_code || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="交付日期" prop="delivery_date" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.delivery_date, '{y}-{m}-{d}') || '--' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <span>共 {{ planTotal }} 条</span>
        <el-pagination
          @size-change="handlePlanSizeChange"
          @current-change="handlePlanCurrentChange"
          :current-page="planParams.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="planParams.pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="planTotal">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 关联工单 -->
    <el-card class="box-card" shadow="never" style="margin-top: 15px;">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold; color: #409EFF;">关联工单</span>
      </div>
      <el-table :data="workOrderList" stripe style="width: 100%">
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="工单编号" prop="work_order_code" align="center" />
        <el-table-column label="工单状态" prop="status" align="center">
          <template slot-scope="scope">
            <el-tag :type="getWorkOrderStatusTagType(scope.row.status)">{{ scope.row.status_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="计划开始日期" prop="plan_start_date" align="center" />
        <el-table-column label="计划结束日期" prop="plan_end_date" align="center" />
        <el-table-column label="优先级" prop="priority" align="center">
          <template slot-scope="scope">
            <el-tag :type="getPriorityTagType(scope.row.priority)">{{ scope.row.priority_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="产品名称" prop="product_name" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.product_name || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品编码" prop="product_code" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.product_code || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物料类型" prop="material_type" align="center" />
        <el-table-column label="制造方式" prop="manufacture_type" align="center" />
      </el-table>
      <div class="pagination-container">
        <span>共 {{ workOrderTotal }} 条</span>
        <el-pagination
          @size-change="handleWorkOrderSizeChange"
          @current-change="handleWorkOrderCurrentChange"
          :current-page="workOrderParams.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="workOrderParams.pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="workOrderTotal">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getProduct } from "@/api/basic/product";
import { getProductionOrder } from "@/api/sc/productionOrder";

export default {
  name: "OrderDetail",
  data() {
    return {
      // 订单ID
      orderId: null,
      // 订单编号
      orderCode: null,
      // 订单信息
      orderInfo: {},
      // 产品列表
      productList: [],
      // 加载状态
      loading: false,
      // 状态数据字典
      statusOptions: [],
      // 优先级数据字典
      priorityOptions: [],
      // 计划列表
      planList: [],
      // 计划分页参数
      planParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 计划总数
      planTotal: 0,
      // 工单列表
      workOrderList: [],
      // 工单分页参数
      workOrderParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 工单总数
      workOrderTotal: 0
    };
  },
  watch: {
    $route(to, from) {
      if (to.query.id) {
        this.orderId = to.query.id;
        console.log('订单详情页面路由变化，刷新数据');
        this.getOrderDetail();
      }
    },
    // 监听订单ID变化
    orderId(newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        console.log('订单ID变化，刷新详情数据');
        this.getOrderDetail();
      }
    }
  },
  created() {
    this.orderId = this.$route.query.id;
    this.orderCode = this.$route.query.prodOrderCode;
    console.log("订单ID:", this.orderId);
    this.getOrderDetail();
    this.getDicts("sc_production_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sc_priority_type").then(response => {
      this.priorityOptions = response.data;
    });
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    
    /** 查询订单详细 */
    getOrderDetail() {
      this.loading = true;
      if (!this.orderId) {
        this.$message.error("订单ID不能为空");
        this.loading = false;
        return;
      }
      
      getProductionOrder(this.orderId).then(response => {
        console.log("接收到的订单详情数据:", response.data);
        console.log("生产计划列表:", response.data.plans);
        console.log("工单列表:", response.data.workOrders);
        
        this.orderInfo = response.data;
        this.productList = response.data.products || [];
        this.planList = response.data.plans || [];
        this.planTotal = this.planList.length;
        this.workOrderList = response.data.workOrders || [];
        this.workOrderTotal = this.workOrderList.length;
        this.loading = false;
      }).catch(error => {
        console.error("获取订单详情出错:", error);
        this.loading = false;
      });
    },
    
    // 根据产品ID获取产品详细信息
    getProductInfoById(productId) {
      return getProduct(productId).then(res => {
        // getProduct返回的是一个AjaxResult，产品信息在data属性中
        return res.data || {};
      });
    },
    
    // 状态标签类型
    getStatusTagType(status) {
      const statusMap = {
        '0': 'info',    // 草稿
        '1': 'warning', // 待计划
        '2': 'primary', // 生产中
        '3': 'success', // 已完成
        '4': 'danger'   // 已取消
      };
      return statusMap[status] || '';
    },
    
    // 获取订单状态名称
    getStatusName(status) {
      // 从状态选项中查找对应的标签
      for (let i = 0; i < this.statusOptions.length; i++) {
        if (this.statusOptions[i].dictValue == status) {
          return this.statusOptions[i].dictLabel;
        }
      }
      // 如果找不到，返回默认值
      const statusNames = {
        '0': '草稿',
        '1': '待计划',
        '2': '生产中',
        '3': '已完成',
        '4': '已取消'
      };
      return statusNames[status] || '待计划';
    },
    
    // 计划状态标签类型
    getPlanStatusTagType(status) {
      const statusMap = {
        '1': 'success', // 未排程
        '2': 'primary', // 已排程
        '3': 'warning'  // 生产中
      };
      return statusMap[status] || '';
    },
    
    // 工单状态标签类型
    getWorkOrderStatusTagType(status) {
      const statusMap = {
        '1': 'info',    // 待下发
        '2': 'primary', // 已下发
        '3': 'warning', // 进行中
        '4': 'success'  // 已完成
      };
      return statusMap[status] || '';
    },
    
    // 获取优先级标签类型
    getPriorityTagType(priority) {
      // 根据优先级设置不同的标签类型
      if (priority == 1) return 'danger';  // 紧急
      if (priority == 2) return 'warning'; // 高
      if (priority == 3) return '';        // 普通
      if (priority == 4) return 'info';    // 低
      if (priority == 5) return 'success'; // 计划
      return '';
    },
    
    // 生产计划分页大小变化
    handlePlanSizeChange(val) {
      this.planParams.pageSize = val;
      // 实际开发需要请求后端API获取数据
    },
    
    // 生产计划页码变化
    handlePlanCurrentChange(val) {
      this.planParams.pageNum = val;
      // 实际开发需要请求后端API获取数据
    },
    
    // 工单分页大小变化
    handleWorkOrderSizeChange(val) {
      this.workOrderParams.pageSize = val;
      // 实际开发需要请求后端API获取数据
    },
    
    // 工单页码变化
    handleWorkOrderCurrentChange(val) {
      this.workOrderParams.pageNum = val;
      // 实际开发需要请求后端API获取数据
    }
  }
};
</script>

<style scoped>
.breadcrumb-container {
  margin-bottom: 15px;
}

.box-card {
  margin-bottom: 20px;
}

.el-divider {
  margin-top: 20px;
  margin-bottom: 20px;
}

.detail-item {
  line-height: 30px;
  margin-bottom: 10px;
}

.label {
  display: inline-block;
  width: 120px;
  text-align: right;
  margin-right: 10px;
  color: #606266;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.pagination-container span {
  margin-right: 10px;
  color: #606266;
}
</style> 